// 记录要删除房屋的id和索引
let houseId = ''
let houseIndex = 0

Page({
  data: {
    dialogVisible: false,
    houseList: [],
    isEmpty: false, // 判断是否有房子
  },

  // ---------------生命周期钩子函数-begin----------------
  onShow() {
    this.getHouseList()
  },
  // ---------------生命周期钩子函数-end------------------

  // ---------------自定义函数-begin-----------------------
  // 1. 获取房屋列表
  async getHouseList() {
    const { code, data: houseList } = await wx.http.get('/room')
    if (code !== 10000) return wx.utils.toast('获取房屋列表失败~')
    this.setData({
      houseList,
      isEmpty: houseList.length === 0,
    })
  },
  // 2. 滑动删除关闭
  swipeClose(ev) {
    const { position, instance } = ev.detail
    console.log(position, instance)
    if (position === 'right') {
      // 显示 Dialog 对话框
      this.setData({
        // 显示提示框
        dialogVisible: true,
      })

      // 记录待删除房屋的id和下标
      houseId = ev.mark.id
      houseIndex = ev.mark.index

      // swiper-cell 滑块关闭
      instance.close()
    }
  },

  // 3. 关闭提示对话框
  dialogClose(ev) {
    // console.log(ev)
    // 3.1 判断: 如果是点击了确认, 调用删除接口函数
    // if (ev.detail === 'confirm') {
    //   this.deleteHouse()
    // }
    ev.detail === 'confirm' && this.deleteHouse()
  },

  // 4. 删除房屋
  async deleteHouse() {
    // console.log('调用删除接口', houseId, houseIndex)
    // 4.1 调用接口
    const { code } = await wx.http.delete('/room/' + houseId)
    if (code !== 10000) return wx.utils.toast('删除房屋失败')
    // 4.2 更新列表(注意: 这里是做本地删除)
    const { houseList } = this.data
    houseList.splice(houseIndex, 1)

    this.setData({
      houseList,
      isEmpty: houseList.length === 0,
    })
  },

  // 5. 去详情页
  goDetail(ev) {
    console.log(ev.mark.id)
    wx.navigateTo({
      url: '/house_pkg/pages/detail/index?id=' + ev.mark.id,
    })
  },

  addHouse() {
    wx.navigateTo({
      url: '/house_pkg/pages/locate/index',
    })
  },
  // ---------------自定义函数-end-------------------------
})
